﻿using Minecraft.CacheRedis;
using Minecraft.Config;
using Minecraft.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Minecraft.BLL.mysql
{
	public class MapBLL : BaseBLL
	{
		private static RedisCacheHelper redisCacheHelper = new RedisCacheHelper();
		private static RedisKey redisKeyEnum = RedisKey.Map;
		public static MapModel GetSingleOrDefault(int playerId, out bool fromCache)
		{
			fromCache = false;
			string redisKey = RedisKeyHelper.GetRedisKeyName(redisKeyEnum, playerId.ToString());
			var cacheModel = redisCacheHelper.StringGet<MapModel>(redisKey);
			if (cacheModel != null)
			{
				fromCache = true;
				return cacheModel;
			}
			else
			{
				var model = new MapModel();
				model = GetSingleOrDefault(model, new KeyValuePair<string, int> ( nameof(model.PlayerId),  playerId ));
				if (model == null)
				{
					model = new MapModel
					{
						PlayerId = playerId,
						SourceMapId = MinecraftConfig.BaseMapId,
						TargetMapId = "",
						TimeTicks = "",
					};
					BatchInsert(new List<MapModel> { model });
				}
				redisCacheHelper.StringSet(redisKey, model, CommonConfig.DefRedisExpiry);
				return model;
			}
		}

		public static bool Update(MapModel model, bool isCacheAfterDbOpt)
		{
			string redisKey = RedisKeyHelper.GetRedisKeyName(redisKeyEnum, model.PlayerId.ToString());
			redisCacheHelper.StringSet(redisKey, model, CommonConfig.DefRedisExpiry);
			if (isCacheAfterDbOpt)
			{
				return Update(model, nameof(model.PlayerId));
			}
			return true;
		}
	}
}
